import React, {Component} from 'react';
import {
  Text,
  View,
  TextInput,
  StyleSheet,
  Button,
  ToastAndroid,
} from 'react-native';
import {connect, DispatchProp} from 'react-redux';
import {add} from '../../store/actions/actions';
import {ToDoType} from '../../store/statesTypes';
import {ToDoDetail} from '../../store/statesTypes';
import { storage } from "../../utils/storage";
import {TODOLIST} from '../../utils/constant';

type Props = ToDoType & DispatchProp

interface State {
}
class HomeAdd extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
  }
  _add = (obj: ToDoDetail)=>{
    this.props.dispatch(add(obj))
  }
  state = {
    item: '',
  };
  OnChangeText = (val: string) => {
    this.setState({
      item: val,
    });
  };
  Submit = () => {
    console.log(this.state.item);
    if (this.state.item) {
      const {navigation} = this.props;
      let obj = {
        title: this.state.item,
        id: String(Date.now())
      }
      this._add(obj)
      ToastAndroid.showWithGravity(
        '添加成功',
        ToastAndroid.SHORT,
        ToastAndroid.CENTER,
      );

      storage.load(TODOLIST, (res)=>{
        const result = {
          data: {
            list: [obj]
          }
        }
        if(res) {
          const list = res.data.list;
          list.push(obj)
          result.data.list = list;
          storage.save(TODOLIST, result);
        }else {
          storage.save(TODOLIST, result);
        }
      })

      navigation.navigate("Home", {t: Date.now()})
    } else {
      ToastAndroid.showWithGravity(
        '请输入内容',
        ToastAndroid.SHORT,
        ToastAndroid.CENTER,
      );
    }
  };
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.add}>待办事项: </Text>
        <TextInput
          style={{height: 40, borderColor: 'gray', borderWidth: 1}}
          onChangeText={(text) => this.OnChangeText(text)}
          value={this.state.item}
        />
        <View style={styles.button}>
          <Button title="提交" onPress={() => this.Submit()} />
        </View>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    padding: 30,
  },
  add: {
    marginBottom: 10,
    fontSize: 20,
  },
  button: {
    marginTop: 30,
  },
});

export default connect()(HomeAdd)
